// pages/bindMobile/bindMobile.js
const wxaUserService = require('../../../../api/wxaUserService.js')
const smsService = require('../../../../api/smsService.js')
const storeService = require('../../../../api/storeService.js')
const auth = require('../../../../utils/auth.js')
const utils = require('../../../../utils/utils.js')
var QQMapWX = require('../../../../libs/qqmap-wx-jssdk.min.js');
var qqmapsdk;

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile: '',
    captcha: '',
    getCodeBtn: "获取验证码",
    getCodeBgColor: '#009F55'
  },
  bindMobileInput: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  bindcaptchaInput: function (e) {
    this.setData({
      captcha: e.detail.value
    })
  },
  getCaptcha: function () {
    if (this.checkMobile() && this.data.getCodeBgColor === '#009F55') {
      var seconds = 60;
      var self = this;
      this.setData({
        getCodeBgColor: '#bbb',
        getCodeBtn: seconds + 's'
      })
      var time = setInterval(function () {
        seconds--;
        self.setData({
          getCodeBtn: seconds + 's'
        })
        if (seconds <= 0) {
          self.setData({
            getCodeBtn: '获取验证码',
            getCodeBgColor: '#009F55'
          })
          clearInterval(time)
        }
      }, 1000)
      smsService.sendSms(this.data.mobile).then(res => {
        console.log(res)
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },
  // 检查手机号
  checkMobile: function () {
    let reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
    if (!this.data.mobile) {
      wx.showToast({
        title: "请填写手机号",
        icon: 'none',
        duration: 2000
      })
      return false;
    } else if (!reg.test(this.data.mobile)) {
      wx.showToast({
        title: "请填写正确的手机号",
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      return true;
    }
  },
  checkCaptcha: function () {
    if (!this.data.captcha) {
      wx.showToast({
        title: "请填写验证码",
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      return true;
    }
  },
  // 前往广告页
  toAdPage: function (e) {
    // 链接
    const url = 'https://xianfengxcx.gomoretech.com/newretail-admin/#/xfAgreement'
    try {
      // let webUrl = url + '&storeId=' + this.data.storeId + '&type=normal'
      let webUrl = url
      wx.setStorageSync('webUrl', webUrl)
    } catch (e) {}
    wx.navigateTo({
      url: '../../advertising/advertising?from=bindMobile'
    })
  },
  bindbox: function () {

  },

  /**
   * 绑定用户手机号
   */
  bindMobile: function (val) {
    console.log(val)
    const that = this
    const loginStatus = this.checkAuth()
    if (loginStatus) {
      if (this.checkMobile() && this.checkCaptcha() && this.data.getCodeBgColor !== '#009F55') {
        try {
          wx.setStorageSync('wj_wxa_formId', val.detail.formId)
        } catch (e) {}
        let storeId = ''
        if (app.globalData.storeInfo) {
          console.log(app.globalData.storeInfo)
          if (app.globalData.systemConfigure.memberAscriptionStoreDistance && app.globalData.storeInfo.distance) {
            let distance = app.globalData.storeInfo.distance
            distance = parseFloat(distance * 1000)
            if (distance < app.globalData.systemConfigure.memberAscriptionStoreDistance) {
              console.log(distance, app.globalData.systemConfigure.memberAscriptionStoreDistance)
              storeId = app.globalData.storeInfo.id
            }
          }
        } else {

        }
        wxaUserService.bindMobile(this.data.mobile, this.data.captcha, 'WXAPP', storeId).then(res => {
          console.log(res)
          if (utils.isHideLoading()) {
            utils.setHideLoading(false)
          }
          if (res.member) {
            auth.setUser(res)
            wx.showToast({
              title: '绑定成功',
              icon: 'none',
              duration: 2000
            })
            app.globalData.userInfo = res
            try {
              wx.setStorageSync('wj_member', res.member)
            } catch (e) {}
          } else {
            wx.showToast({
              title: '绑定失败',
              icon: 'none',
              duration: 2000
            })
          }
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 2000);
        }).catch(err => {
          console.log(err)
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        })
      } else {
        if (this.data.getCodeBgColor === '#009F55') {
          wx.showToast({
            title: '请获取验证码！',
            icon: 'none',
            duration: 2000
          })
        }
      }
    } else {
      wx.showToast({
        title: '您还未授权登陆，请登陆后绑定手机号哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 检查当前用户是否登录授权
  checkAuth: function () {
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    this.getMemberUserInfo()
    const self = this
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'AD5BZ-CHCKS-64OOD-6G6TX-BSOA6-IFF3V'
    });
    if (app.globalData.addressInfo) {
      console.log(app.globalData.addressInfo)
      let latitude = app.globalData.addressInfo.lat;
      let longitude = app.globalData.addressInfo.lng;
      self.getAllStoreInfo(latitude, longitude);
    } else {
      //1、获取当前位置坐标
      wx.getLocation({
        type: 'gcj02',
        success: function (res) {
          let latitude = res.latitude
          let longitude = res.longitude
          // 2.根据当前位置，获取最近的几个门店信息
          self.getAllStoreInfo(latitude, longitude);
        }
      })
    }
  },
  getMemberUserInfo: function () {
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: "您还未授权，请登陆授权",
        icon: 'none',
        duration: 2000
      })
    } else {

    }
  },
  // 获取所有门店信息
  getAllStoreInfo: function (latitude, longitude) {
    const self = this
    try {
      var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
      if (tempAllStores) {
        // Do something with return value
        let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
        app.globalData.storeInfo = tempAllStores[tempIndex];
        // 获取当前位置到最近门店的距离
        self.calcStoreDistance(tempAllStores[tempIndex], latitude, longitude)
      } else {
        // 查询所有门店
        storeService.queryList().then(res => {
          var allStores = [];
          res.forEach(item => {
            if (item.status === 'OPEN') {
              allStores.push(item)
            }
          });
          try {
            wx.setStorageSync('wj_allStores', allStores)
          } catch (e) {
            console.log(e)
          }
          let tempIndex = self.getNearestStore(allStores, latitude, longitude);
          return allStores[tempIndex]
        }).then(res => {
          app.globalData.storeInfo = res;
          self.calcStoreDistance(res, latitude, longitude)
        })
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = utils.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },
  // 获取用户到门店的距离
  calcStoreDistance: function (stores, latitude, longitude) {
    let dis = utils.distance(latitude, longitude, stores.latitude, stores.longitude);
    let store = {
      ...stores,
      distance: dis
    }
    app.globalData.storeInfo = store
    this.setData({
      storeInfo: store
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})